package ld.oauth.blog.service.file.impl;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import ld.oauth.blog.service.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public  class FileServiceImpl implements FileService {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private  FdfsWebServer fdfsWebServer;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    public String uploadFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        // 获取文件扩展名
        String extension = FilenameUtils.getExtension(fileName);
        // 文件元数据信息
        Set<MetaData> metaData = new HashSet<>(4);
        metaData.add(new MetaData("fileName",fileName));
        // 上传文件
        StorePath storePath = null;
        try {
            storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), extension, metaData);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("文件上传路径:[{}]",storePath.getFullPath());
        String viewPath = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        log.info("可访问路径:[{}]",viewPath);

        extension = FilenameUtils.getExtension(viewPath);
        String xthumbPath = viewPath.replace("." + extension, "")+"_150x150."+extension;
        log.info("缩略图路径:[{}]",xthumbPath);
        return viewPath;
    }

    /**
     * 下载文件
     */
    @Override
    public void downloadFile(String filePath, HttpServletResponse response) {
        log.info("需要下载的文件:[{}]",filePath);
        String group = filePath.substring(0, filePath.indexOf("/"));
        String path = filePath.substring(filePath.indexOf("/") + 1);
        Set<MetaData> metadata = fastFileStorageClient.getMetadata(group, path);
        String fileName = metadata.iterator().next().getValue();
        byte[] bytes = fastFileStorageClient.downloadFile(group, path, new DownloadByteArray());
        response.setContentType("application/octet-stream");
        try {
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, Charsets.UTF_8.displayName()));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            IOUtils.write(bytes,response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

    @Override
    public void deleteImg(String fileUrl) throws Exception {
        int i = fileUrl.indexOf("group");//group首次出现的位置索引
        int j = fileUrl.indexOf("M");//M首次出现的位置索引
        String groupName = fileUrl.substring(i, j - 1);
        String remoteFilename = fileUrl.substring(j);
        fastFileStorageClient.deleteFile(groupName, remoteFilename);
    }
}

